/*
 * Copyright (c) 2012-2020
 * All Rights Reserved by Thunder Software Technology Co., Ltd and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with THUNDERSOFT in writing by applicable law.
 *
 * Auther: Chi Qing  <chiqing0601@thundersoft.com>
 * Function Description: This program is used to set memory usage.
 */

#include <iostream>
#include <unistd.h>
using namespace std;

typedef long long int int64;
static const int64 g_memTotalSize = sysconf(_SC_PAGESIZE)*sysconf(_SC_PHYS_PAGES); //单位：B
static const int64 g_memFreeSize = sysconf(_SC_PAGESIZE)*sysconf(_SC_AVPHYS_PAGES); // 字节
 
static int *p[1024*1024*15] = {0};  //每个元素将会申请1kb内存，差不多管理15GB, 数组本身=1024*1024*15*8=120MB

void occupyMemory(const int64 size, const double minute)
/*
 * name: occupyMemory
 * params: const int64 size, size(KB) of memory  will be occupied with type of int64
 *                    const int minute, how long will be occypied(miute).
 * return: none 
 * usage: occupy size of memory in minute. 
 */
{
    int curr_size = 0;

    /*16*1024*1024*1024/1024*/
    while(curr_size < size/1024) 
    {
        p[curr_size] = (int *)malloc(1024); //一次申请1kb内存
        curr_size++;
    }
    cout << "内存占用中..." << endl;
    while(true){};
    sleep(minute*60);
    curr_size = 0;
    while(curr_size < size/1024)
    {
        free(p[curr_size]);
        curr_size++;
    }
}


int  main()
{
    int64 num = 0;
    int64 memSize = 0;
    double minute;

    cout << "请输入需占用内存比例(单位：%): ";
    cin >> num;
    cout << "请输入需占用时间(单位：分): ";
    cin >> minute;

    memSize = g_memTotalSize*num/100; //字节
    if(memSize > g_memFreeSize)
    {
        cout << "超出可分配空间" << endl;
        exit(1);
    }

    occupyMemory(memSize, minute);
    cout << "时间已到，内存已释放" << endl;
    exit(0);
}

